package account

import (
	"context"
	"database/sql"
	"time"

	"user/internal/biz"
	"user/internal/svc"
	"user/internal/types"
	"user/models"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 用户注册
func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RegisterLogic) Register(req *types.RegisterReq) (resp *types.RegisterResp, err error) {

	//1. select by username
	usersModel := models.NewUsersModel(l.svcCtx.SqlConn)
	user, err := usersModel.FindByUsername(l.ctx, req.Username)
	if err != nil {
		return nil, biz.DBError
	}

	if user != nil {
		return nil, biz.AlreadyRegister

	}
	//2. it is not exist, insert
	_, err = usersModel.Insert(l.ctx, &models.Users{
		Username:         req.Username,
		Password:         req.Password,
		RegistrationTime: time.Now(),
		LastLoginTime: sql.NullTime{
			Time:  time.Now(),
			Valid: true,
		},
	})
	if err != nil {
		return nil, biz.DBError
	}
	return &types.RegisterResp{}, nil
}
